#include "music.h"
#include <malloc.h>
#include <stddef.h>
#include <string.h>

void create_musicvec(musicvec_t *vecptr, size_t len) {
  vecptr->cap = len;
  vecptr->len = len;
  vecptr->data = calloc(vecptr->cap, sizeof(MusicNode));

  if (!vecptr->data) {
    fprintf(stderr, "[%s, %d] %s", __FILE__, __LINE__,
            "failed to create musicvec\n");
    return;
  }
}

void delete_musicvec(musicvec_t *vecptr) {
  free(vecptr->data);
  memset(vecptr, 0, sizeof(musicvec_t));
}

void musicvec_push_back(musicvec_t *v, MusicNode const *musicptr) {
  if (v->len == v->cap) {
    v->cap <<= 1;
    MusicNode *tmp = malloc(v->cap * sizeof(MusicNode));
    memcpy(tmp, v->data, v->len * sizeof(MusicNode));
  }

  v->data[v->len++] = *musicptr;
}

void create_musictask(musictask_t *taskptr, size_t music_num) {
  create_musicvec(&taskptr->musicvec, music_num);
}

void delete_musictask(musictask_t *taskptr) {
  delete_musicvec(&taskptr->musicvec);
}

MusicNode *get_musicptr(musicvec_t *vecptr, size_t index) {
  return index < vecptr->len ? &vecptr->data[index] : NULL;
}

static void print_musicnode(MusicNode *mn) {
  printf("{ %d/%s/%s/%s }\n", mn->number, mn->name, mn->info, mn->singer);
}

void print_musictask(musictask_t *taskptr) {
  musicvec_t *vecptr = &taskptr->musicvec;

  printf("{\n");
  printf("\tdevice_id: %s\n", taskptr->device_id);
  printf("\tdevice_name: %s\n", taskptr->device_name);
  printf("\tsonglist: [\n");

  for (int i = 0; i < vecptr->len; ++i) {
    printf("\t\t");
    print_musicnode(get_musicptr(vecptr, i));
  }
  printf("\t]\n");
  printf("}\n");
}
